define (require, exports, module) ->
  # 加载样式
  require 'mods/pay/pay_css.css'
  utils =  require 'mods/utils/utils_mod'
  pay_api = require 'mods/pay/pay_api'
  # 定义组件
  module.exports = Vue.extend

    # 组件模板
    template: require 'mods/pay/pay_tpl.js'

    # 定义变量
    data: () ->
      # 是否加载完成
      loadedSucc: false
      # 加载失败提示语
      loadedFail: ''
      # 错误提示
      errorMsg: ''
      # 选择银行的指针
      selectYhIdx: -1
      # 选择银行
      select_yh: ''
      # 验证码是否正确
      identify_exit: false
      # 验证码
      identify_val: ''
      # 银行名称
      bankTable:[
        {
          bank_name:"工商银行"
          bank_no:"703"
          bank_no_t:"001"
        },
        {
          bank_name:"农业银行"
          bank_no:"704"
          bank_no_t:"002"
        },
        {
          bank_name:"中国银行"
          bank_no:"705"
          bank_no_t:"003"
        },
        {
          bank_name:"建设银行"
          bank_no:"706"
          bank_no_t:"004"
        },        
        {
          bank_name:"交通银行"
          bank_no:"707"
          bank_no_t:"005"
        },
        # {
        #   bank_name:"招商银行"
        #   bank_no:"708"
        #   bank_no_t:"006"
        # },
        # {
        #   bank_name:"实业银行"
        #   bank_no:"709"
        #   bank_no_t:"007"
        # },
        {
          bank_name:"浦发银行"
          bank_no:"716"
          bank_no_t:"014"
        },
        {
          bank_name:"兴业银行"
          bank_no:"715"
          bank_no_t:"013"
        },
        {
          bank_name:"民生银行"
          bank_no:"712"
          bank_no_t:"009"
        },
        {
          bank_name:"上海银行"
          # bank_no:"17"
        },
        {
          bank_name:"平安银行"
          bank_no:"714"
          bank_no_t:"012"
        }
      ]
      # 在线支付产品信息
      buyProdInfo: {}
      # 在线支付步骤
      paySteps: 0
      # 用户信息
      userInfo: {}
      # 短信验证码是否为空
      identifyValIsEmpty: true
      # 对话框选项
      dlgOpt: {state: false}
      # 加载弹出框
      dlgOptLoad: {state: false}
      # 验证码错误
      error_rz:''
      # 验证码倒计时
      time:60
      # 验证码
      yzm2_loading:false
      # 银行卡
      card_no:''
      # 姓名
      name:''
      # 证件有效期
      card_expire:''
      # 地址
      address:''
      # 职业
      profession:''
      # 是否认证成功
      rz_success:false
      # 手机号
      phone:''
      # 签约订单
      order:{}
      # 协议显示隐藏
      up_down:[]
      # 按钮是否选中
      payMethod:-1
      # 协议列表
      xieyiList: []
      # 交易密码
      password:""
      # 确认交易密码
      password_two:""
      # 校验交易密码
      check_password:""
      # 密码错误
      error_password:""
      # 确认密码错误
      error_password2:""
      # 开户错误
      error_msg:""
      # 激活
      jihuo:false

    # 定义方法
    methods:

      # 插件加载
      pluginLoad: () ->
        self = @

      # 加载成功
      loadedSuccFunc: () ->
        self = @
        self.$nextTick () ->
          # 加载成功标识
          self.loadedSucc = true
          # 插件加载
          self.pluginLoad()

      # 在线支付步骤2提交
      onSubmit2: () ->
        self = @
        if !self.validateForm()
          return

        self.yzm_btn_value = '获取验证码'
        self.identity_tip = false
        if false is self.identify_exit
          self.identify_dialog = true
          return
        self.$router.push {path:'/pay/3'}

      # 查看详情
      goDetail: (_id) ->
        self = @
        self.$router.push '/product/' + _id

      # 获取手机验证码
      getIdentify: () ->
        self = @
        # if !self.validateForm()
        #   return
        self.savePaySignContract()

      # 将快捷支付数据保存在数据库
      savePaySignContract: ()->
        self = @
        # 将银行卡号保存在sessionstroge
        sessionStorage.setItem 'card_no', self.card_no.replace(/\s+/g,'')
        self.clordid = self.getKOrderId()
        params = 
          'payment':
            clordid : self.clordid
            mobile : self.userInfo.phone
            certificate_no : self.userInfo.id_no
            name : self.name
            card_no : self.card_no.replace(/\s+/g,'')
            user_name : self.userInfo.name
        # 保存快捷支付信息
        pay_api.savePaySignContract params
          .then (res)->
            self.paySignContract()
          .catch (err)->
            self.errorMsg = err

      # 签约
      paySignContract: ()->
        self = @
        lunxun = ''
        # 清除定时轮询
        clearInterval(lunxun)
        params =
          'signContract':
            ClOrdID : self.clordid
            Mobile : self.userInfo.phone
            CertificateNo : self.userInfo.id_no
            InvestorName : self.name
            BankAccount : self.card_no.replace(/\s+/g,'')
            # BankCode:$scope.vars.sel_bank?.bank_code
            BankCode : '0310'
            OTCAccount : self.userInfo.name
            MerchantNo : '1234566'
        # $scope.act.yzmDialog()
        # 发送签约请求
        $.ajax({
          type: "POST",
          url: "/apprest/pay/sign_contract",
          dataType:'json',
          data : params,
          success: (msg)->
            tmp = msg
          error:(error)->
            self.errorMsg = error || '网络异常或其它原因'
          });

        # 轮询次数
        time = 0
        # 每秒轮询本地数据库看是否返回签约信息
        lunxun = setInterval ()->
          time +=  1
          if time==15
            # 清除定时轮询
            clearInterval(lunxun)
            self.errorMsg = '网络异常，请求超时'
          params =
            'clordid':self.clordid
          pay_api.queryPastPayOrder params
            .then (res)->
              if res?.body?.data[0].signContract
                self.yzm_loading = false
                # 清除定时轮询
                clearInterval(lunxun)
                if res?.body?.data[0].signContract?.success
                  # 重新获取验证码时候
                  # if self.yzmDialog
                  #   return
                  self.yzmDialog()
                else
                  self.errorMsg = res?.data[0].signContract?.msg
            .catch (err)->
              self.errorMsg = err?.error || '查询快捷支付订单失败'
        ,2000
        return false

      # 验证码弹出框
      yzmDialog: ()->
        self = @
        dlgTipsObj =
          state:true
          width:500
          title:'请输入验证码'
          closeBt:true
          ok:()->
            self.dlgOpt.state = false
          cancel:()->
            self.dlgOpt.state = false
        self.dlgOpt = Vue.util.extend {}, dlgTipsObj
        timer = ''
        clearInterval(timer)
        timer = setInterval ()->
          self.time -= 1
          if self.time == 0
            clearInterval(timer)
        ,1000

      # 认证 快捷支付输入验证码后点击确定
      payVerification: ()->
        self = @
        lunxun = ''
        # 清除定时轮询
        clearInterval(lunxun)
        self.yzm2_loading =  true
        # 生成认证的订单号
        rz_clordid = self.getKOrderId()
        params =
          'verification':
            MerchantNo : '1234566'
            ClOrdID : rz_clordid
            OrigClOrdID : self.clordid
            BankAccount : self.card_no.replace(/\s+/g,'')
            CertificateNo : self.userInfo.id_no
            DigitalSignature : self.identify_val
            OTCAccount : self.userInfo.name
        #发送认证请求
        $.ajax({
          url:'/apprest/pay/verification',
          type:'POST',
          data:params,
          dataType:'json',
          success:(msg)->
            # console.log msg
            tmp = msg
          error:(error)->
            self.error_rz = error || '网络异常或其它原因'
          })
        # 轮询次数
        time = 0
        # 每秒轮询本地数据库看是否返回认证信息
        lunxun = setInterval ()->
          time +=  1
          if time==15
            # 清除定时轮询
            clearInterval(lunxun)
            self.error_rz = '网络异常，请求超时'
          params =
            'clordid':self.clordid
          pay_api.queryPastPayOrder params
            .then (res)->
              if res?.body?.data[0].verification
                for item in res?.body?.data[0].verification
                  if item?.rz_clordid == rz_clordid
                    self.yzm2_loading = false
                    # 清除定时轮询
                    clearInterval(lunxun)
                    # 验证码校验成功
                    if item?.success && item?.clientid
                      # $scope.vars.kPayInfo['past_ClientID'] = item?.clientid
                      self.order = res?.body?.data[0]
                      self.rz_success = true
                      # 关闭弹出框
                      self.dlgOpt.state = false
                      break
                    else
                      self.error_rz = item?.msg
            .catch (err)->
              self.error_rz = err
        ,2000

      # 激活
      goActive: ()->
        self = @
        self.jhDialog()

      # 点击激活成功按钮
      activeSuc: ()->
        self = @
        params =
          'clordid':self.clordid
        pay_api.queryPastPayOrder params
          .then (res)->
            if res?.body?.data[0]?.active
              if res?.body?.data[0]?.active?.success
                self.dlgOptLoad.state = false
                self.paySteps = 0
              # else
              #   self.jihuo = false
                # self.error_rz = item?.msg
          # .catch (err)->
          #   self.error_rz = err

      # 激活状态弹出框
      jhDialog: ()->
        self = @
        dlgTipsObj =
          state:true
          width:425
          title:'激活状态'
          # closeBt:true
          ok:()->
            self.dlgOptLoad.state = false
          cancel:()->
            self.dlgOptLoad.state = false
        self.dlgOptLoad = Vue.util.extend {}, dlgTipsObj

      # 快捷支付生成订单ID
      getKOrderId: () ->
        self = @
        currYmd = utils.dateToStr new Date()
        randomStr = self.getRandNum 5
        return "#{currYmd}#{randomStr}"

      # 获得N位随机数
      getRandNum: (n) ->
        rnd = ""
        for i in [0...n]
          rnd += Math.floor(Math.random()*10)
        return rnd

      # 点击选择银行的类别
      selectYhType: (id) ->
        self = @
        self.selectYhIdx = id
        self.select_yh = self.bankTable[id]
        # 将选择的银行卡放在sessionstroge
        sessionStorage.setItem 'select_yh',self.select_yh

      # 银行卡校验
      CheckBankNo: (t_bankno) ->
        self = @
        bankno = t_bankno
        _bankno = ('' + bankno).replace(/\s+/g,'')
        
        # 是否输入银行卡
        if bankno is ''
          self.errorMsg = '请填写银行卡号'
          return false

        # 银行卡位数校验
        if _bankno.length < 16 or _bankno.length > 21
          self.errorMsg = '银行卡号长度必须在16到21之间'
          return false

        #开头6位
        strBin = '10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99'
        if strBin.indexOf(_bankno.substring(0, 2)) == -1
          self.errorMsg = '银行卡号开头6位不符合规范'
          return false

        # Luhm算法校验银行卡
        tmp_fuc = self.luhmCheck _bankno
        # Luhm校验
        if not tmp_fuc
          return false
        return true

      # 银行卡校验是否有效
      luhmCheck: (bankno)->
        self = @
        # target = angular.element('#error-message')
        lastNum = bankno.substr(bankno.length - 1, 1)
        #取出最后一位（与luhm进行比较）
        first15Num = bankno.substr(0, bankno.length - 1)
        #前15或18位
        newArr = new Array
        i = first15Num.length - 1
        while i > -1
          #前15或18位倒序存进数组
          newArr.push first15Num.substr(i, 1)
          i--
        arrJiShu = new Array
        # 奇数位*2的积 <9
        arrJiShu2 = new Array
        # 奇数位*2的积 >9
        arrOuShu = new Array
        # 偶数位数组
        j = 0
        while j < newArr.length
          if (j + 1) % 2 == 1
            #奇数位
            if parseInt(newArr[j]) * 2 < 9
              arrJiShu.push parseInt(newArr[j]) * 2
            else
              arrJiShu2.push parseInt(newArr[j]) * 2
          else
            arrOuShu.push newArr[j]
          j++
        jishu_child1 = new Array
        # 奇数位*2 >9 的分割之后的数组个位数
        jishu_child2 = new Array
        # 奇数位*2 >9 的分割之后的数组十位数
        h = 0
        while h < arrJiShu2.length
          jishu_child1.push parseInt(arrJiShu2[h]) % 10
          jishu_child2.push parseInt(arrJiShu2[h]) / 10
          h++
        sumJiShu = 0
        # 奇数位*2 < 9 的数组之和
        sumOuShu = 0
        # 偶数位数组之和
        sumJiShuChild1 = 0
        # 奇数位*2 >9 的分割之后的数组个位数之和
        sumJiShuChild2 = 0
        # 奇数位*2 >9 的分割之后的数组十位数之和
        sumTotal = 0
        m = 0
        while m < arrJiShu.length
          sumJiShu = sumJiShu + parseInt(arrJiShu[m])
          m++
        n = 0
        while n < arrOuShu.length
          sumOuShu = sumOuShu + parseInt(arrOuShu[n])
          n++
        p = 0
        while p < jishu_child1.length
          sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p])
          sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p])
          p++
        #计算总和
        sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2)
        #计算Luhm值
        k = if parseInt(sumTotal) % 10 == 0 then 10 else parseInt(sumTotal) % 10
        luhm = 10 - k
        luhm = luhm.toString()
        if lastNum is luhm
          return true
        else
          self.errorMsg = '请输入正确的卡号'
          return false

      # 验证填写信息
      validateForm: () ->
        self = @
        if '' is self.select_yh
          self.errorMsg = '请选择银行'
          return false

        if '' is self.card_no
          self.errorMsg = '储蓄卡号不能为空'
          return false

        # if !self.CheckBankNo(self.card_no)
        #   # self.errorMsg = '储蓄卡号不能为空'
        #   return false

        if '' is self.name
          self.errorMsg = '姓名不能为空'
          return false

        if self.name.match(/[^\u4e00-\u9fa5]/g)
          self.errorMsg = '姓名只能输入汉字'
          return false

        if '' is self.card_expire
          self.errorMsg = '证件有效期不能为空'
          return false

        if self.card_expire < new Date() || self.card_expire == new Date()
          self.errorMsg = '证件有效期不对'
          return false

        if '' is self.address
          self.errorMsg = '联系地址不能为空'
          return false

        if self.address.match /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im
          self.errorMsg = '联系地址不能输入特殊字符'
          return false
 
        if '' is self.profession
          self.errorMsg = '职业不能为空'
          return false

        if '' is self.phone
          self.errorMsg = '银行预留手机号不能为空'
          return false
        return true

      # 控制交易密码必填和位数
      openKhh: ()->
        self = @
        self.error_password = ''
        self.error_password2 = ''
        if '' is self.password
          self.error_password = '交易密码不能为空'
          return
        if self.password.length<6
          self.error_password = '交易密码长度不能小于6位'
          return
        if self.password.length>16
          self.error_password = '交易密码长度不能大于16位'
          return
        if '' is self.password_two
          self.error_password2 = '确认交易密码不能为空'
          return
        # 开通客户号
        self.openClient()

      # 开通客户号
      openClient:()->
        self = @
        id_begindate = self.userInfo.id_begindate
        id_begindate = id_begindate.substr(0,4)+id_begindate.substr(5,2)+id_begindate.substr(8,2)
        id_enddate = self.userInfo.id_enddate
        id_enddate = id_enddate.substr(0,4)+id_enddate.substr(5,2)+id_enddate.substr(8,2)
        # 默认参数
        params =
          "op_branch_no": 8888,
          "op_station": "",
          "op_entrust_way": "7",
          "branch_no": 8888,
          "prodta_no": "87",
          "client_name":self.userInfo.name,
          "full_name":self.userInfo.name,
          "client_gender":"0"
          "nationality": "CHN",
          "dsorgan_flag": "0",
          "id_kind":self.userInfo.id_kind,
          "id_no":self.userInfo.id_no,
          "id_begindate":parseInt id_begindate
          "id_enddate":parseInt id_enddate
          "password":self.password,
          "action_in": 1,
          "mobile_tel": "",
          "contact_name": "",
          "contact_id_kind": "",
          "contact_id_no": "",
          "agency_no": "GF9"
        pay_api.openClient params
          .then (res)->
            console.log res,'GP18001002158'
            if res?.body && res?.body?.error_no == 0
              client_id = res?.body?.client_id
              self.openSecum(client_id)
            else
              self.error_msg = res?.body?.error_info
          .catch (error)->
            self.error_msg = error or error?.error

      # 开通理财账户
      openSecum: (client_id)->
        self = @
        params =
          # op_branch_no:8888
          op_station:''
          op_entrust_way:"7"
          # branch_no:8888
          client_id:client_id
          prodta_no:"87"
          # client_rights:"CEVetW"
          id_kind:self.userInfo.id_kind
          id_no:self.userInfo.id_no
          agency_no:"GF9"
        pay_api.openSecum params
          .then (res)->
            console.log res,"0008700002328","87GP1800100215801","DPAY181002154"
            if res?.body && res?.body?.error_no == 0
              self.openTrans(client_id)
            else
              self.error_msg = res?.body?.error_info
          .catch (error)->
            self.error_msg = error or error?.error

      # 开通交易账户
      openTrans: (client_id)->
        self = @
        pay_account = sessionStorage.getItem 'card_no'
        bank = sessionStorage.getItem 'select_yh'
        params =
          op_station:''
          op_entrust_way:"7"
          client_id:client_id
          prodta_no:"87"
          pay_account:pay_account
          pay_kind:"4"
          money_type:"0"
          bank_no:bank?.bank_no
          bank_name:bank?.bank_name
          # dsbank_city:""
          # Shdc_payer_bank_name:""

        # 开通交易账户
        pay_api.openTrans params
          .then (res)->
            if res?.body && res?.body?.error_no == 0
              # 开通成功，查询是否签署产品协议
              self.queryContract(client_id)
              # self.paySteps = 1
            else
              self.error_msg = res?.body?.error_info
          .catch (error)->
            self.error_msg = error or error?.error

      # 查询是否签署协议
      queryContract: (client_id)->
        self = @
        client_id = 'GP18001002161'
        params = 
          "client_id":client_id
          "prodta_no":"87"
          "prod_code":"ZB0024"
        # 查询是否签署合同
        pay_api.queryContract params
          .then (res)->
            if res?.body && res?.body?.error_no == 0
              # 如果未签署
              if res?.body?.sign_flag == 0
                # 查询该产品对应的合同
                self.queryProdContract()
              # 已经签署合同
              else
                self.paySteps = 2
            else
              self.error_msg = res?.body?.error_info
          .catch (err)->
            self.error_msg = err or err?.error

      # 查询产品对应的合同
      queryProdContract: ()->
        self = @
        params = 
          "prodta_no":"87"
          "prod_code":"ZB0024"
        pay_api.queryProdContract params
          .then (res)->
            if res?.body?.error_no == 0
              # 产品有合同时
              if res?.body?.table_data && res?.body?.table_data.length>0
                for item in res?.body?.table_data
                  item["up_down"] = true
                  self.xieyiList.push item
                self.paySteps = 1
              # 产品没合同时
              else
                self.paySteps = 2
            else
              self.error_msg = self.error_info
          .catch (err)->
            self.error_msg = err or err?.error

      # 签署协议
      signXieyi: ()->
        self = @
        self.paySteps = 2

      # 订单确定
      orderConfirm:()->
        self = @

      # 下一步
      nextStep: ()->
        self = @
        self.paySteps = 3

      # 选择支付方式
      selectPayMethod: (payMethod)->
        self =  @
        # if payMethod == 0
        self.payMethod = payMethod
        # else if payMethod == 1
        #   self.

      # 在线支付
      pay: ()->
        self = @
        self.paySteps = 4

      # 从session中获取用户信息
      getUserInfo: () ->
        self = @
        user_info_str = sessionStorage.getItem 'userInfo'
        self.userInfo = JSON.parse user_info_str

      # 查询用户是否签约认证过
      getIsRz: ()->
        self = @
        params =
          user_name : self.userInfo.name
        pay_api.queryPastPayOrderAll params
          .then (res)->
            if res?.body
              for item in res?.body
                if item?.verification
                  for verifi in item.verification
                    # 如果认证成功
                    if verifi?.success
                      self.rz_success = true
                      self.order = item
                      break
                    # break
          .catch (err)->
            console.log err

      # 依赖组件
      components:
        'c-dialog': require 'mods/dialog/dialog_mod'
        # 'c-pay-step': require 'mods/pay/pay_step/pay_step_mod'

    created: () ->
      self = @
      # 获取用户信息
      self.getUserInfo()
      self.buyProdInfo = self.$route.params
      self.buyProdInfo.ddbh = '123456789'
      # self.getIsRz()

    # 计算属性
    computed:

      # 加载中的样式
      loaddingClass: () ->
        self = @
        if self.loadedSucc
          return 'c-hidden'
        if self.loadedFail
          return 'c-hidden'
        return ''

      # 加载成功的样式
      loadedSuccClass: () ->
        self = @
        return if self.loadedSucc then '' else 'c-vhidden'

      # 加载失败的样式
      loadedFailClass: () ->
        self = @
        return if self.loadedFail then '' else 'c-hidden'

      # 控制
      isMatchPsw: ()->
        self = @
        self.error_password2 = ''
        if !!self.password && '' isnt self.password && '' isnt self.password_two
          if self.password == self.password_two
            return 'yes'
          else
            return 'no'

      check_password: ()->
        self = @
        if !!self.password && '' isnt self.password
          return 'yes'
        else
          return 'no'

    # 组件初始化
    mounted: () ->
      self = @
      # 加载成功 - 处理函数
      return self.loadedSuccFunc()